Java If-else
Java If-else Statement
- if statement
- if-else statement
- if-else-if ladder
- nested if statement
Java if Statement
Syntax:
if(condition){
//code to be executed
}
Example:
//Java Program to demonstate the use of if statement.
public classIfExample {
public static voidmain(String[] args) {
//defining an 'age' variable
intage=20;
//checking the age
if(age>18){
System.out.print("Age is greater than 18");
}
}
}
Output:
Age is greater than 18
Java if-else Statement
Syntax:
if(condition){
//code if condition is true
} else{
//code if condition is false
}
Example:
//A Java Program to demonstrate the use of if-else statement.
//It is a program of odd and even number.
public classIfElseExample {
public static voidmain(String[] args) {
//defining a variable
intnumber=13;
//Check if the number is divisible by 2 or not
if(number%2==0){
System.out.println("even number");
}else{
System.out.println("odd number");
}
}
}
Output:
odd number
Using Ternary Operator
Java if-else-if ladder Statement
Syntax:
if(condition1){
//code to be executed if condition1 is true
} else if(condition2){
//code to be executed if condition2 is true
}
else if(condition3){
//code to be executed if condition3 is true
}
else{
//code to be executed if all the conditions are false
}
Java Nested if statement
Syntax:
if(condition){
//code to be executed
if(condition){
//code to be executed
}
}
Example:
public class JavaNestedIfExample2 {
public static void main(String[] args) {
//Creating two variables for age and weight
int age=25;
int weight=48;
//applying condition on age and weight
if(age>=18){
if(weight>50){
System.out.println("You are eligible to donate blood");
} else{
System.out.println("You are not eligible to donate blood");
}
} else{
System.out.println("Age must be greater than 18");
}
}}
Output:
You are not eligible to donate blood